package com.example.avmanagerweb.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.avmanagerweb.Utils.AESUtil;
import com.example.avmanagerweb.Utils.String.StringUtils;
import com.example.avmanagerweb.Utils.String.StringValidator;
import com.example.avmanagerweb.Utils.Token.UniqueTokenUtil;
import com.example.avmanagerweb.entity.*;
import com.example.avmanagerweb.entity.vo.*;
import com.example.avmanagerweb.redisService.RedisService;
import com.example.avmanagerweb.result.RLIST;
import com.example.avmanagerweb.result.exceptionhandler.JWException;
import com.example.avmanagerweb.service.SysDepartmentService;
import com.example.avmanagerweb.service.SysDevicService;
import com.example.avmanagerweb.service.SysUserinfoService;
import com.example.avmanagerweb.service.UserKeyService;
import jdk.nashorn.internal.ir.CallNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xg
 * @since 2023-08-16
 */
@RestController
@RequestMapping("/sys-userinfo")
public class SysUserinfoController {

   @Autowired
   private SysDepartmentService sysDepartmentService;

    @Autowired
    private SysUserinfoService sysUserinfoService;

    @Autowired
    private SysDevicService sysDevicService;
    @Autowired
    private UserKeyService userKeyService;
    @Autowired
    private RedisService redisService;

    @PostMapping("/login")
    public RLIST login(@RequestBody LoginVo loginVo){
        if(loginVo == null){
            return RLIST.error().message("参数异常");
        }
        if(StringUtils.isEmpty(loginVo.getUserAcc())){
            return RLIST.error().message("账号异常");
        }
        if(StringUtils.isEmpty(loginVo.getUserpwd())){
            return RLIST.error().message("密码异常");
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uLoginName",loginVo.getUserAcc());
        wrapper.eq("uIsDel",false);
        SysUserinfo one = sysUserinfoService.getOne(wrapper);
        if(one == null){
            return RLIST.error().message("账户不存在");
        }
        // 解密数据
        String decryptedData = null;
        try {
            decryptedData = AESUtil.decrypt(loginVo.getUserpwd());
        } catch (Exception e) {
            throw new JWException(401,"密码错误");
        }
        System.out.println("Decrypted Data: " + decryptedData);
        if(!one.getUpwd().equals(decryptedData)){
            return  RLIST.error().message("密码错误");
        }

        return RLIST.ok().data("data", one);
    }

    @PostMapping("/login2")
    public RLIST login2(@RequestBody LoginVo loginVo){
        if(loginVo == null){
            return RLIST.error().message("参数异常");
        }
        if(StringUtils.isEmpty(loginVo.getUserAcc())){
            return RLIST.error().message("账号异常");
        }
        if(StringUtils.isEmpty(loginVo.getUserpwd())){
            return RLIST.error().message("密码异常");
        }
        if(StringUtils.isEmpty(loginVo.getKey())){
            return RLIST.error().message("key异常");
        }
        if(StringUtils.isEmpty(loginVo.getSignature())){
            return RLIST.error().message("signature异常");
        }
        QueryWrapper wrapperUser = new QueryWrapper();
        wrapperUser.eq("user_key",loginVo.getKey());
        UserKey oneUser = userKeyService.getOne(wrapperUser);
        if(oneUser == null){
            return RLIST.error().message("key不存在");
        }


        Login2Vo login2Vo = new Login2Vo();
        login2Vo.setUserAcc(loginVo.getUserAcc());
        login2Vo.setUserpwd(loginVo.getUserpwd());
        login2Vo.setKey(loginVo.getKey());

        String jsonString = JSON.toJSONString(login2Vo);
        System.out.println(jsonString);

        try {
            String encrypt = com.example.avmanagerweb.Utils.EncryptionUtil.AESUtil.encrypt(jsonString,oneUser.getSecretKey());
            if(!encrypt.equals(loginVo.getSignature())){
                return RLIST.error().message("密钥异常");
            }

        } catch (Exception e) {
            throw new JWException(401,"验证异常");
        }


        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uLoginName",loginVo.getUserAcc());
        wrapper.eq("uIsDel",false);
        SysUserinfo one = sysUserinfoService.getOne(wrapper);
        if(one == null){
            return RLIST.error().message("账户不存在");
        }
        // 解密数据
        String decryptedData = null;
        try {
            decryptedData = AESUtil.decrypt(loginVo.getUserpwd(),oneUser.getSecretKey());
        } catch (Exception e) {
//            e.printStackTrace();
            throw new JWException(401,"密码错误");
        }
        System.out.println("Decrypted Data: " + decryptedData);
        if(!one.getUpwd().equals(decryptedData)){
            return  RLIST.error().message("密码错误");
        }

        //生成token
        String token = UniqueTokenUtil.generateToken();
        redisService.setTokenValue(token,1L, one.getUid());
//        redisService.setValue(one.getUid());
        String userStr = JSON.toJSONString(one);
        System.out.println(userStr);
        redisService.setValue(one.getUid()+"",userStr);
        return RLIST.ok().data("data", one).data("token",token);
    }

    @PostMapping("/getUser")
    public RLIST getUser(@RequestBody SysUserinfoVo sysUserinfoVo, HttpServletRequest request){
        //查询自己部门
        String token = request.getHeader("token");
        Integer value = (Integer) redisService.getValue(token);
        System.out.println(value);
        if( value == null || value == 0 ) {
            return RLIST.error().message("token异常 出现bug");
        }

        //校验
        if(sysUserinfoVo.getPageNo() <= 0){
            //当前页
            return RLIST.error().message("页数异常");
        }
        if(sysUserinfoVo.getPageSize() <= 0){
            //每页条数
            return RLIST.error().message("页条数异常");
        }



        String  json = (String) redisService.getValue(value+"");
        JSONObject jsonObject = JSONObject.parseObject(json);
        SysUserinfo sysUserinfo = JSON.toJavaObject(jsonObject, SysUserinfo.class);
        Integer id = sysUserinfo.getUdepid();
        if(id== null ||id <= 0){
            return RLIST.error().message("异常 账号无部门id");
        }
        List<SysDepartment> departmentList = sysDepartmentService.getSubquery(id);


        Page<SysUserinfo> page = new Page<>(sysUserinfoVo.getPageNo(), sysUserinfoVo.getPageSize());
        QueryWrapper  wrapper = new QueryWrapper();
        Integer uid = sysUserinfoVo.getUid();
        Integer udepid = sysUserinfoVo.getUdepid();
        String uloginname = sysUserinfoVo.getUloginname();
        String uname = sysUserinfoVo.getUname();
        if(uid != null && uid != 0){
            wrapper.eq("uId",uid);
        }
        if(udepid != null && udepid != 0){
            boolean fla = true;
            for (SysDepartment sysDepartment : departmentList) {
                if(sysDepartment.getDepid() == udepid){
                    fla = false;
                    break;
                }
            }
            if(fla){
                return RLIST.error().message("无法跨部门查询");
            }
            wrapper.eq("uDepId",udepid);
        }else {

            List<Integer> depIdList = new ArrayList<>();
            if(departmentList == null || departmentList.size()<=0 ){
                return RLIST.error().message("查询子部门结构异常");
            }
            for (SysDepartment sysDepartment : departmentList) {
                depIdList.add(sysDepartment.getDepid());
            }
            wrapper.in("uDepId", depIdList);
        }
        if(!StringUtils.isEmpty(uloginname)){
            wrapper.like("uLoginName",uloginname);
        }
        if(!StringUtils.isEmpty(uname)){
            wrapper.like("uName",uname);
        }

        wrapper.orderByDesc("uId");

        Page pageList = sysUserinfoService.page(page, wrapper);

        //总条数
        long total = pageList.getTotal();
        List<SysUserinfo> list = pageList.getRecords();
        //页码总数
        long numPage = 0;
        if (total == 0) {
            numPage = 1L;
        } else if (list.size() == 0) {
            numPage = 1L;
        } else {
            numPage = (long) Math.ceil(total / (double) sysUserinfoVo.getPageSize());
        }
        return RLIST.ok().data("data", list).data("total", total).data("numPage", numPage);
    }

    //删除
    @DeleteMapping("/delUser")
    public RLIST delUser(@RequestParam("delid") Integer delid, HttpServletRequest request){
        //查询自己部门
        String token = request.getHeader("token");
        Integer value = (Integer) redisService.getValue(token);
        System.out.println(value);
        if( value == null || value == 0 ) {
            return RLIST.error().message("token异常 出现bug");
        }
        String  json = (String) redisService.getValue(value+"");
        JSONObject jsonObject = JSONObject.parseObject(json);
        SysUserinfo sysUserinfo = JSON.toJavaObject(jsonObject, SysUserinfo.class);
        Integer id = sysUserinfo.getUdepid();
        if(id== null ||id <= 0){
            return RLIST.error().message("异常 账号无部门id");
        }
        List<SysDepartment> departmentList = sysDepartmentService.getSubquery(id);

        SysUserinfo userinfo = sysUserinfoService.getById(delid);
        if(userinfo == null){
            return RLIST.error().message("用户不存在");
        }
        boolean fla = true;
        for (SysDepartment sysDepartment : departmentList) {
            if(sysDepartment.getDepid() == userinfo.getUdepid()){
                fla = false;
                break;
            }
        }
        if(fla){
            return RLIST.error().message("无法跨部门查询");
        }
        boolean remove = sysUserinfoService.removeById(delid);
        boolean b = redisService.delKeyData(String.valueOf(delid));
        Long aLong = redisService.deleteKeyByValue(String.valueOf(delid));
        if(remove){
            return RLIST.ok();
        } else {
            return RLIST.error();
        }

    }

    //用户添加
    @PostMapping("/addUser")
    public RLIST addUser(@RequestBody UserinfoVo userinfoVo, HttpServletRequest request){
        SysUserinfo userinfo = new SysUserinfo();
        userinfo.setUdepid(userinfoVo.getUdepid());
        userinfo.setUloginname(userinfoVo.getUloginname());
        userinfo.setUpwd(userinfoVo.getUpwd());
        userinfo.setUname(userinfoVo.getUname());
        userinfo.setUdvid(userinfoVo.getUdvid());
        userinfo.setUphone(userinfoVo.getUphone());
        userinfo.setUpolno(userinfoVo.getUpolno());
        if(userinfoVo.getUusertype() != null && userinfoVo.getUusertype() != 0){
            if(userinfoVo.getUusertype() == 1){
                userinfo.setUissysmana(true);
            } else if(userinfoVo.getUusertype() == 2){
                userinfo.setUisdepartmana(true);
            }
        } else {
            userinfoVo.setUusertype(3);
        }
        userinfo.setUusertype(userinfoVo.getUusertype());

        System.out.println(userinfo.toString());

        //查询自己部门
        String token = request.getHeader("token");
        Integer value = (Integer) redisService.getValue(token);
        System.out.println(value);
        if( value == null || value == 0 ) {
            return RLIST.error().message("token异常 出现bug");
        }



        if(userinfo.getUdepid() == null || userinfo.getUdepid() <= 0){
            return RLIST.error().message("部门id不能为空");
        }
        if(StringUtils.isEmpty(userinfo.getUloginname())){
            return RLIST.error().message("登录名不能为空");
        }
        boolean validAccount = StringValidator.isValidAccount(userinfo.getUloginname());
        if(!validAccount){
            return RLIST.error().message("登录名异常 持数字和字母 长度6-12");
        }

        if(StringUtils.isEmpty(userinfo.getUpwd())){
            return RLIST.error().message("密码能为空");
        }
//        因为MD5加密无法校验格式
//        boolean validPwd = StringValidator.isValidPwd(userinfo.getUpwd());
//        if(!validPwd){
//            return RLIST.error().message("登录名异常 持数字和字母 长度6-12");
//        }
        if(StringUtils.isEmpty(userinfo.getUname())){
            return RLIST.error().message("用户名称为空");
        }
        boolean validNanem = StringValidator.isValidStringNanem(userinfo.getUname());
        if(!validNanem){
            return RLIST.error().message("用户名称异常 持数字和字母-汉字 长度2-12");
        }


        if(StringUtils.isEmpty(userinfo.getUpolno())){
            return RLIST.error().message("用户编号称为空");
        }
        boolean validpolno = StringValidator.isValidAccount(userinfo.getUpolno());
        if(!validpolno){
            return RLIST.error().message("用户编号异常 持数字和字母 长度6-12");
        }

        if(!StringUtils.isEmpty(userinfo.getUphone())){
            boolean validPhone = StringValidator.isValidPhoneNumber(userinfo.getUphone());
            if(!validPhone){
                return RLIST.error().message("手机号码格式异常");
            }
        }


        //用户登录名同名校验
        QueryWrapper wrapperName = new QueryWrapper();
        wrapperName.eq("uLoginName", userinfo.getUloginname());
        int countName = sysUserinfoService.count(wrapperName);
        if(countName>0) {
            return RLIST.error().message("登录名存在");
        }
        //用户编号同名校验
        QueryWrapper wrapperPolno = new QueryWrapper();
        wrapperPolno.eq("uPolNo", userinfo.getUpolno());
        int countPolno = sysUserinfoService.count(wrapperPolno);
        if(countPolno > 0) {
            return RLIST.error().message("用户编号存在");
        }



        //查询自己部门2
        String  json = (String) redisService.getValue(value+"");
        JSONObject jsonObject = JSONObject.parseObject(json);
        SysUserinfo sysUserinfo = JSON.toJavaObject(jsonObject, SysUserinfo.class);
        Integer id = sysUserinfo.getUdepid();
        if(id== null ||id <= 0){
            return RLIST.error().message("账号无部门id");
        }
        List<SysDepartment> departmentList = sysDepartmentService.getSubquery(id);

        boolean fla = true;
        for (SysDepartment sysDepartment : departmentList) {
            if(sysDepartment.getDepid() == userinfo.getUdepid()){
                fla = false;
                break;
            }
        }
        if(fla){
            return RLIST.error().message("无法跨部门添加");
        }


        boolean save = sysUserinfoService.save(userinfo);
        if(save) {
            return RLIST.ok();
        } else {
            return RLIST.error();
        }

    }

    //用户修改
    @PostMapping("/alterUser")
    public RLIST alterUser(@RequestBody UserinfoVo userinfoVo, HttpServletRequest request){
        //查询自己部门
        String token = request.getHeader("token");
        Integer value = (Integer) redisService.getValue(token);
        System.out.println(value);
        if( value == null || value == 0 ) {
            return RLIST.error().message("token异常 出现bug");
        }



        SysUserinfo userinfo = new SysUserinfo();
        userinfo.setUid(userinfoVo.getId());
        userinfo.setUdepid(userinfoVo.getUdepid());
        userinfo.setUpwd(userinfoVo.getUpwd());
        userinfo.setUname(userinfoVo.getUname());
        userinfo.setUdvid(userinfoVo.getUdvid());
        userinfo.setUphone(userinfoVo.getUphone());
        if(userinfoVo.getUusertype() != null && userinfoVo.getUusertype() != 0){
            if(userinfoVo.getUusertype() == 1){
                userinfo.setUissysmana(true);
                userinfo.setUisdepartmana(false);
            } else if(userinfoVo.getUusertype() == 2){
                userinfo.setUissysmana(false);
                userinfo.setUisdepartmana(true);
            } else {
                userinfo.setUissysmana(false);
                userinfo.setUisdepartmana(false);
            }
        }
        userinfo.setUusertype(userinfoVo.getUusertype());
        System.out.println(userinfo.toString());


        if(!StringUtils.isEmpty(userinfo.getUname())){
            boolean validNanem = StringValidator.isValidStringNanem(userinfo.getUname());
            if(!validNanem){
                return RLIST.error().message("用户名称异常 持数字和字母 长度6-12");
            }
        }

        if(!StringUtils.isEmpty(userinfo.getUpwd())){
            //校验
        }


        if(!StringUtils.isEmpty(userinfo.getUphone())){
            boolean validPhone = StringValidator.isValidPhoneNumber(userinfo.getUphone());
            if(!validPhone){
                return RLIST.error().message("手机号码格式异常");
            }
        }

        //查询设备是否存在
//        SysDevic byId = sysDevicService.getById(userinfoVo.getUdvid());
//        if(byId == null){
//            return RLIST.error().message("设备不存在");
//        }

        if(userinfo.getUdepid() != null && userinfo.getUdepid() != 0){

            //查询自己部门2
            String  json = (String) redisService.getValue(value+"");
            JSONObject jsonObject = JSONObject.parseObject(json);
            SysUserinfo sysUserinfo = JSON.toJavaObject(jsonObject, SysUserinfo.class);
            Integer id = sysUserinfo.getUdepid();
            if(id== null ||id <= 0){
                return RLIST.error().message("账号无部门id");
            }
            List<SysDepartment> departmentList = sysDepartmentService.getSubquery(id);

            boolean fla = true;
            for (SysDepartment sysDepartment : departmentList) {
                if(sysDepartment.getDepid() == userinfo.getUdepid()){
                    fla = false;
                    break;
                }
            }
            if(fla){
                return RLIST.error().message("无法跨部门修改");
            }


        }
        boolean b = sysUserinfoService.updateById(userinfo);
        if(b){
            return RLIST.ok();
        } else {
            return RLIST.error();
        }



    }


    //批量删除
    @DeleteMapping("delUserList")
    public RLIST delUserList(@RequestBody DelUserListVo delUserListVo, HttpServletRequest request){
        //查询自己部门
        String token = request.getHeader("token");
        Integer value = (Integer) redisService.getValue(token);
        System.out.println(value);
        if( value == null || value == 0 ) {
            return RLIST.error().message("token异常 出现bug");
        }
        //查询自己部门2
        String  json = (String) redisService.getValue(value+"");
        JSONObject jsonObject = JSONObject.parseObject(json);
        SysUserinfo sysUserinfo = JSON.toJavaObject(jsonObject, SysUserinfo.class);
        Integer id = sysUserinfo.getUdepid();
        if(id== null ||id <= 0){
            return RLIST.error().message("账号无部门id");
        }





        if(delUserListVo.getId() == null || delUserListVo.getId() <= 0) {
            return RLIST.error().message("操作id异常");
        }
        if(sysUserinfo.getUid() != delUserListVo.getId()) {
            return RLIST.error().message("操作id不匹配");
        }
        if(delUserListVo.getDelList() == null || delUserListVo.getDelList().size() <= 0) {
            return RLIST.error().message("删除id异常");
        }
        List<Integer> listByIds = delUserListVo.getDelList();
        System.out.println(listByIds.toArray());
        if(listByIds == null || listByIds.size() == 0){
            return RLIST.error();
        }
        List<SysDepartment> departmentList = sysDepartmentService.getSubquery(id);


        boolean remove = sysUserinfoService.    removeList(departmentList, listByIds);
        if(remove){
            return RLIST.ok();
        } else {
            return RLIST.error();
        }
    }

}

